package router

import (
	"context"
	"log"
	"net/http"
	"time"

	"gin-gateway/core/init"
	"github.com/gin-gonic/gin"
)

func DashboardHttpServerRun() {
	gin.SetMode(Init.GetStringConf("base.base.debug_mode"))
	HttpSrvHandler = &http.Server{
		Addr:           Init.GetStringConf("base.http.addr"),
		Handler:        InitDashboardRouter(),
		ReadTimeout:    time.Duration(Init.GetIntConf("base.http.read_timeout")) * time.Second,
		WriteTimeout:   time.Duration(Init.GetIntConf("base.http.write_timeout")) * time.Second,
		MaxHeaderBytes: 1 << uint(Init.GetIntConf("base.http.max_header_bytes")),
	}
	go func() {
		log.Printf("[INFO] DashboardHttpServerRun: %s\n", Init.GetStringConf("base.http.addr"))
		if err := HttpSrvHandler.ListenAndServe(); err != nil {
			log.Fatalf("[ERROR] DashboardHttpServerRun:%s err:%v\n", Init.GetStringConf("base.http.addr"), err)
		}
	}()
}

func DashboardHttpServerStop() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := HttpSrvHandler.Shutdown(ctx); err != nil {
		log.Fatalf("[ERROR] DashboardHttpServerStop err:%v\n", err)
	}
	log.Printf("[INFO] DashboardHttpServerStop stopped\n")
}
